 /*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

 /**
 * Project  : WebQQCore
 * Package  : iqq.im.protocol
 * File     : CheckVerifyAction.java
 * Author   : solosky < solosky772@qq.com >
 * Created  : 2012-9-1
 * License  : Apache License 2.0 
 */
package com.windmill.action;

import iqq.im.QQActionListener;
import iqq.im.QQException.QQErrorCode;
import iqq.im.action.AbstractHttpAction;
import iqq.im.core.QQContext;
import iqq.im.event.QQActionEvent;
import iqq.im.http.QQHttpRequest;
import iqq.im.http.QQHttpResponse;

import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.script.ScriptEngine;

import org.json.JSONArray;
import org.json.JSONException;

import com.windmill.bean.Card;
import com.windmill.bean.Compose;
import com.windmill.bean.Gift;
import com.windmill.bean.ThemeCard;
import com.windmill.core.CardConstants;
import com.windmill.core.CardStore;
import com.windmill.util.JavaScriptUtils;

/**
 *获取魔卡卡片V3版本所有信息
 *
 */
public class GetCardInfoV3Action extends AbstractHttpAction {
	private CardStore cardStore;
	public GetCardInfoV3Action(CardStore cardStore, QQContext context, QQActionListener listener) {
		super(context, listener);
		this.cardStore = cardStore;
	}

	

	@Override
	public void onHttpStatusOK(QQHttpResponse response) {
		ScriptEngine engine = JavaScriptUtils.getScriptEngine();		
		try {
			engine.eval(response.getResponseString());
			JSONArray themeCardArray = new JSONArray(engine.eval("theme_card_list.toJSON()").toString()),
					  cardArray = new JSONArray(engine.eval("card_list.toJSON()").toString()),
					  giftArray = new JSONArray(engine.eval("gift_list.toJSON()").toString()),
					  themeComposeArray = new JSONArray(engine.eval("theme_compose_list.toJSON()").toString());
			initCardList(cardArray);
			initGiftList(giftArray);
			initThemeCardList(themeCardArray);
			initComposeList(themeComposeArray);
			if(getActionListener()!=null){
				notifyActionEvent(QQActionEvent.Type.EVT_OK, cardStore);
			}
		} catch (Exception e) {
			System.out.println("初始化 CardStore 错误。");
			notifyActionEvent(QQActionEvent.Type.EVT_ERROR, QQErrorCode.UNEXPECTED_RESPONSE);
		}        
	}

	
	private void initCardList(JSONArray cardArray) throws JSONException {
		Card card = null;
		for(int i=0;i<cardArray.length();i++){
			card = new Card();
			JSONArray arry = cardArray.getJSONArray(i);
			card.setId(arry.getInt(0));
			card.setThemeId(arry.getInt(1));
			//card_id,theme_id,CardName,Price,Type,PickRate, Enable, version, time, item no, [mana]
			//[29,40,'鍩庡競琛楅亾',40,1,0,1,1,0,1027529,[0]],
			card.setName(arry.getString(2));
			card.setPrice(arry.getInt(3));
			card.setType(arry.getInt(4));
			card.setPickRate(arry.getInt(5));
			card.setEnable(arry.getInt(6));
			card.setVersion(arry.getInt(7));
			card.setTime(arry.getInt(8));
			card.setItemNo(arry.getInt(9));	
			int[] mana = new int[arry.getJSONArray(10).length()];
			for(int j=0;j<arry.getJSONArray(10).length();j++){
				mana[j] = arry.getJSONArray(10).getInt(j);
			}
			card.setMana(mana);
			cardStore.getCardMap().put(card.getId(), card);
		}
	}

	private void initGiftList(JSONArray giftArray) throws JSONException {
		//gift_id, gift_type,szTYPE_ID,gift_name	
		//[24,1,'454051','modify'],
		Gift gift = null;
		for(int i=0;i<giftArray.length();i++){
			gift = new Gift();
			JSONArray arry = giftArray.getJSONArray(i);
			gift.setId(arry.getInt(0));
			gift.setType(arry.getInt(1));
			gift.setSzTYPE_ID(arry.getString(2));
			gift.setName(arry.getString(3));
			cardStore.getGiftMap().put(gift.getId(),gift);
		}
	}
	private void initComposeList(JSONArray themeComposeArray) throws JSONException {
		//theme_id,state,cardtar,card1,card2,card3,costtime
		Compose compose = null;
		for(int i=0;i<themeComposeArray.length();i++){
			compose = new Compose();
			JSONArray arry = themeComposeArray.getJSONArray(i);
			compose.setThemeId(arry.getInt(0));
			compose.setState(arry.getInt(1));
			compose.setCardtar(arry.getInt(2));
			compose.setCard1(arry.getInt(3));
			compose.setCard2(arry.getInt(4));
			compose.setCard3(arry.getInt(5));
			compose.setCostTime(arry.getInt(6));
			cardStore.getComposeMap().put(compose.getCardtar(),compose);
		}
	}
	private void initThemeCardList(JSONArray themeCardArray) throws JSONException {
		ThemeCard themeCard = null;
		for(int i=0;i<themeCardArray.length();i++){
			themeCard = new ThemeCard();
			JSONArray arry = themeCardArray.getJSONArray(i);
			themeCard.setId(arry.getInt(0));
			themeCard.setName(arry.getString(1));
			themeCard.setDifficulty(arry.getInt(2));
			themeCard.setPublishTime(arry.getInt(3));
			themeCard.setPickRate(arry.getInt(4));
			themeCard.setEnable(arry.getInt(5));
			themeCard.setPrize(arry.getInt(6));
			themeCard.setScore(arry.getInt(7));
			themeCard.setColor(arry.getInt(8));
			
			String[] tempGift = arry.getString(9).split("\\|");
			Set<Gift> gifts = new HashSet<Gift>();
			Pattern p = Pattern.compile("\\d+");				
			for(int j=0;j<tempGift.length;j++){
				Matcher m = p.matcher(tempGift[j]);
				if(m.find()){
					gifts.add(cardStore.getGiftById(Integer.valueOf(m.group())));					
				}
			}
			themeCard.setGift(gifts);			
			themeCard.setText(arry.getString(10));		
			Card[] cards = new Card[arry.getJSONArray(11).length()];
			for(int j=0;j<arry.getJSONArray(11).length();j++){
				cards[j] = cardStore.getCardById(arry.getJSONArray(11).getInt(j));
				cards[j].setTheme(themeCard);
			}
			themeCard.setCards(cards);
			themeCard.setType(arry.getInt(12));
			themeCard.setVersion(arry.getInt(13));
			themeCard.setTime(arry.getInt(14));
			themeCard.setOfftime(arry.getInt(15));
			themeCard.setFlashSrcTid(arry.getInt(16));
			themeCard.setUnKnow(arry.getInt(17));//17
			cardStore.getThemeCardMap().put(themeCard.getId(), themeCard);
		}
	}



	@Override
	public QQHttpRequest buildRequest() {
		QQHttpRequest req = createHttpRequest("GET", CardConstants.CARD_INFO_V3);
		req.addHeader("Accept", "application/javascript, */*;q=0.8");
		req.addHeader("Accept-Language", "zh-CN");
		req.addHeader("Proxy-Connection", "Keep-Alive");
		req.addHeader("DNT", "1");
		req.addHeader("Pragma", "no-cache");
		req.addHeader("Host", "appimg2.qq.com");		
		req.addHeader("Referer", "http://appimg2.qq.com/card/index_v3.html");
		return req;
	}
}
